from flask import Flask, render_template, request, redirect, url_for, session
import config
import pymysql
pymysql.install_as_MySQLdb()
from models import User
from exts import db
import json

app = Flask(__name__)
app.config.from_object(config)
app.secret_key = '123456'
db.init_app(app)

#首页
@app.route('/')
def hello_world():
    return render_template('index.html')


# 测试
@app.route('/testRestful/<int:_id>')
def testRestful(_id):
    print(_id)
    return json.dumps({"id": _id})


# 测试
@app.route('/testGet')
def testGet():
    _id = request.values.get("id")
    return json.dumps({"id": _id})
    pass


#登陆接口
@app.route('/login/', methods = ['GET', 'POST'])
def login():
    if request.method == 'GET':
       return render_template('login.html')
    else:
        telephone = request.form.get('telephone')
        password = request.form.get('password')
        #查表
        user = User.query.filter(User.telephone == telephone, User.password == password).first()
        if user:
            session['user_id'] = user.id
            session.permanent = True
            # print ('--%s', session['user_id'])
            return render_template('index.html', user = user.username)
        else:
            return u'手机号码或者密码错误'


#注册接口
@app.route('/regist/', methods=['GET','POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        telephone = request.form.get('telephone')
        username = request.form.get('username')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        #手机号码验证，如果被注册了就不能在注册
        user = User.query.filter(User.telephone == telephone).first()
        if user:
            return '该手机号码已经被注册'
        else:
            #password1要和password2相等
            if password1 !=password2:
                return u'两次密码不想等，请核对后再填写'
            else:
               user = User(telephone=telephone, username=username, password=password1)
               db.session.add(user)
               db.session.commit()
               #如果注册成功过。页面跳转到登录
               return  redirect(url_for('login'))



#注销
@app.route('/logout/', methods = ['GET', 'POST'])
def logout():
    return render_template('index.html', user = '')


#发布文章
# @app.route()

#上下文登录状态
#这边就不做历史缓存了
# @app.context_processor
# def my_context_processor():
#     user_id = session.get('user_id')
#     if user_id:
#         user = User.query.filter(User.telephone == user_id).first()
#         if user:
#             return {'user': user}
#     return {}
if __name__ == '__main__':
    app.run()
